/*!
  @file message-impl.h
  @copyright 2013 Kubota Lab. All rights resereved.
*/

#include <arpa/inet.h>
#include "core/io.h"

inline const char* Message::encode() {
  resize();

  uint32_t id = htonl(id_);
  uint32_t body_len = htonl(getBodyLength());

  char *pos = data_.get();
  memcpy(pos, &id, sizeof(id));
  pos += sizeof(id);
  memcpy(pos, &body_len, sizeof(body_len));
  pos += sizeof(body_len);
  memcpy(pos, getBodyData(), sizeof(body_len));

  return data_.get();
}

inline void Message::decode() {
  char *pos = data_.get();

  uint32_t id = ntohl(*reinterpret_cast<uint32_t*>(pos));
  if (id != id_) {
    ERROR("Decode error: Invalid ID " << id_ << ", " << id);
    return;
  }
  pos += sizeof(id);

  uint32_t body_len = ntohl(*reinterpret_cast<uint32_t*>(pos));
  data_len_ = HEADER_LEN + body_len;
  pos += sizeof(body_len);

  setBodyData(pos, body_len);
}

inline void Message::resize() {
  size_t body_len = getBodyLength();
  if (data_len_ < HEADER_LEN + body_len) {
    data_len_ = HEADER_LEN + body_len;
    data_.reset(new char(data_len_));
    //INFO("alloced " << data_len_ << " B");
  }
}
